<template>
  <view class="detail-container">
    <view class="nav-title">{{ isEdit ? '编辑室友' : '添加室友' }}</view>
    
    <view class="form-wrapper">
      <view class="form-card">
        <view class="form-title">基本信息</view>
        
        <uni-forms ref="form" :model="formData" :rules="rules" label-position="top" :border="false">
          <uni-forms-item label="姓名" name="name">
            <uni-easyinput 
              class="form-input" 
              v-model="formData.name" 
              placeholder="请输入姓名" 
              placeholder-class="placeholder"
              :disabled="formData.verifyStatus === 1"
            />
          </uni-forms-item>
          
          <uni-forms-item label="联系方式" name="contacts">
            <uni-easyinput 
              class="form-input" 
              v-model="formData.contacts" 
              placeholder="请输入联系方式" 
              placeholder-class="placeholder"
              type="number"
              maxlength="11"
              :disabled="formData.verifyStatus === 1"
            />
          </uni-forms-item>
          
          <uni-forms-item label="身份证号" name="idCardNumber" >
            <uni-easyinput 
              class="form-input" 
              v-model="formData.idCardNumber" 
              placeholder="请输入身份证号" 
              placeholder-class="placeholder"
              maxlength="18"
              :disabled="formData.verifyStatus === 1"
            />
          </uni-forms-item>
        </uni-forms>
      </view>
      
      <view class="form-card" v-if="isEdit || showVerifySection">
        <view class="form-title">认证信息</view>
        
        <view class="verify-info">
          <view class="verify-status verified" v-if="formData.verifyStatus === 1">
            <text class="verify-icon">✓</text>
            <text class="verify-text">已完成人脸认证</text>
          </view>
          
          <view class="face-photo-section" v-if="formData.verifyStatus === 1">
            <text class="photo-label">人脸照片</text>
            <view class="photo-container">
              <image :src="formData.picUrl" mode="aspectFill" class="face-image"></image>
            </view>
          </view>
          
          <view v-else>
            <view class="verify-status unverified">
              <text class="verify-icon">!</text>
              <text class="verify-text">未完成人脸认证</text>
            </view>
            
            <view class="verify-tip">
              <text class="tip-text">完成人脸认证后，可以使用更多功能</text>
            </view>
            
            <button class="verify-button" @click="goToVerify">
              <text class="button-text">去认证</text>
              <text class="button-icon">→</text>
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <view class="action-area">
      <button class="action-button cancel" @click="goBack">取消</button>
      <button class="action-button submit" @click="saveCohabitant">保存</button>
    </view>
  </view>
</template>

<script>
import { phonePattern, idCardPattern } from '@/utils/common'
import { addCohabitant, updateCohabitant, cohabitantDetail } from '@/api/renter'
export default {
  data() {
    return {
      isEdit: false,
      showVerifySection: false, // 控制添加状态下是否显示认证信息模块
      formData: {
        id: '',
        name: '',
        contacts: '',
        idCardNumber: '',
        verifyStatus: 2,
        picUrl: '',
        mainFlag: "0",
        checkInId: '',
        apartmentId: '',
        renterId: '',
      },
      // 表单校验规则
      rules: {
        name: {
          rules: [
            { required: true, errorMessage: '请输入姓名' }
          ]
        },
        contacts: {
          rules: [
            { required: true, errorMessage: '请输入联系方式' },
            { pattern: phonePattern(), errorMessage: '请输入正确的手机号码' }
          ]
        },
        idCardNumber: {
          rules: [
            { required: true, errorMessage: '请输入身份证号' },
            { 
              validateFunction: (rule, value, data, callback) => {
                // 检查是否包含连续的8个*，如果是则免校验
                if (/\*{8}/.test(value)) {
                  callback(); // 通过校验
                } else {
                  // 否则校验身份证格式
                  if (!idCardPattern().test(value)) {
                    callback('请输入正确的身份证号');
                  } else {
                    callback(); // 通过校验
                  }
                }
              }
            }
          ]
        }
      }
    }
  },
  onLoad(options) {
    // 判断是否为编辑模式
    if (options.renterId) {
      this.isEdit = true
      this.getCohabitantDetail(options.renterId);
    } else {
      // 新增模式
      this.formData.apartmentId = options.apartmentId
      this.formData.checkInId = options.checkInId
      this.formData.mainFlag = '0'
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    getCohabitantDetail(renterId) {
      cohabitantDetail(renterId).then(res => {
        this.formData = res.data
      })
    },
    saveCohabitant() {
      // 使用uni-forms进行表单校验
      this.$refs.form.validate().then(result => {
        console.log('表单校验结果：', result)
        // 表单校验通过
        // 保存室友信息
        uni.showLoading({
          title: '保存中...'
        })
        
        // 根据是否为编辑模式调用不同的API
        const savePromise = this.isEdit 
          ? updateCohabitant(this.formData) 
          : addCohabitant(this.formData)
        
        savePromise.then(res => {
          uni.hideLoading()
          
          if (res.code === 200) {
            // 如果是添加状态，保存成功后显示认证信息模块
            if (!this.isEdit) {
              // 更新ID，以便后续操作
              if (res.renterId) {
                this.formData.renterId = res.renterId
              }
              
              this.showVerifySection = true
              uni.showToast({
                title: '保存成功，请完成认证',
                icon: 'none',
                duration: 2000
              })
            } else {
              // 编辑状态下直接返回
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              })
              
              // 返回上一页
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            }
          } else {
            // 保存失败
            uni.showToast({
              title: res.message || '保存失败',
              icon: 'none'
            })
          }
        }).catch(err => {
          uni.hideLoading()
          uni.showToast({
            title: '保存失败，请稍后重试',
            icon: 'none'
          })
          console.error('保存室友信息失败:', err)
        })
      }).catch(errors => {
        // 表单校验失败
        console.log('表单错误：', errors)
        
        // 显示第一个错误信息
        if (errors && errors.length > 0) {
          uni.showToast({
            title: errors[0].errorMessage || '表单填写有误，请检查',
            icon: 'none',
            duration: 2000
          })
        }
      })
    },
    goToVerify() {
      // 跳转到人脸认证页面，携带用户基本信息
      uni.navigateTo({
        url: `/pages/home/face-verify/index?name=${this.formData.name}&contacts=${this.formData.contacts}&idCardNumber=${this.formData.idCardNumber}&renterId=${this.formData.renterId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f8f9fc;
  display: flex;
  flex-direction: column;
  padding-bottom: 140rpx; /* 为底部按钮留出空间 */
  
  .nav-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333333;
    padding: 30rpx;
    text-align: left;
  }
  
  .form-wrapper {
    flex: 1;
    padding: 0 30rpx 30rpx 30rpx;
    
    .form-card {
      background-color: #ffffff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 30rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
      
      .form-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 30rpx;
        position: relative;
        padding-left: 20rpx;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 8rpx;
          height: 32rpx;
          background: linear-gradient(135deg, #4a90e2, #6773e9);
          border-radius: 4rpx;
        }
      }
      
      :deep(.uni-forms-item) {
        margin-bottom: 30rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .uni-forms-item__label {
          font-size: 28rpx;
          color: #333333;
          margin-bottom: 16rpx;
          line-height: 1.2;
          padding: 0;
        }
        
        .uni-forms-item__content {
          .uni-forms-item__error {
            color: #f56c6c;
            font-size: 24rpx;
            margin-top: 8rpx;
          }
        }
        
        .form-input {
          width: 100%;
          height: 90rpx;
          background-color: #f5f7fa;
          border-radius: 12rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          color: #333333;
          box-sizing: border-box;
        }
        
        .placeholder {
          color: #999999;
        }
      }
      
      .verify-info {
        .verify-status {
          display: flex;
          align-items: center;
          padding: 16rpx 24rpx;
          border-radius: 12rpx;
          margin-bottom: 30rpx;
          
          .verify-icon {
            font-size: 32rpx;
            margin-right: 16rpx;
          }
          
          .verify-text {
            font-size: 28rpx;
          }
          
          &.verified {
            background-color: rgba(76, 175, 80, 0.1);
            color: #4caf50;
          }
          
          &.unverified {
            background-color: rgba(255, 152, 0, 0.1);
            color: #ff9800;
          }
        }
        
        .verify-tip {
          margin-bottom: 30rpx;
          
          .tip-text {
            font-size: 26rpx;
            color: #666666;
          }
        }
        
        .verify-button {
          display: flex;
          justify-content: center;
          align-items: center;
          background: linear-gradient(135deg, #ff9800, #ff7043);
          height: 90rpx;
          border-radius: 45rpx;
          box-shadow: 0 6rpx 16rpx rgba(255, 152, 0, 0.3);
          
          .button-text {
            font-size: 30rpx;
            color: #ffffff;
            font-weight: 500;
            margin-right: 10rpx;
          }
          
          .button-icon {
            font-size: 30rpx;
            color: #ffffff;
          }
        }
        
        .face-photo-section {
          .photo-label {
            display: block;
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 16rpx;
          }
          
          .photo-container {
            width: 200rpx;
            height: 200rpx;
            border-radius: 12rpx;
            overflow: hidden;
            background-color: #f5f7fa;
            
            .face-image {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
    }
  }
  
  .action-area {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    background-color: #ffffff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
    
    .action-button {
      width: 48%;
      height: 90rpx;
      border-radius: 45rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30rpx;
      font-weight: 500;
      &::after {
        border: none;
      }
      
      &.cancel {
        background-color: #f5f7fa;
        color: #666666;
        border: 1rpx solid #e5e5e5;
      }
      
      &.submit {
        background: linear-gradient(135deg, #4a90e2, #6773e9);
        color: #ffffff;
        box-shadow: 0 6rpx 16rpx rgba(73, 143, 226, 0.3);
      }
    }
  }
}
</style>
